package com.bjsxt.chapter13_iterator;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName ConcreteMyAggregate
 * @Description 自定义的聚合类
 * @Author 黑马程序员
 * @Date 14:50 2024/6/23
 * @Version 1.0
 **/
public class ConcreteMyAggregate {


    private List<Object> list = new ArrayList<>();


    public ConcreteMyAggregate() {

    }

    public void addObject(Object obj){
        list.add(obj);
    }

    public void removeObject(Object obj){
        list.remove(obj);
    }

    // 获得迭代器
    public MyIterator createIterator(){
        return new ConcreteIterator();
    }


    // 使用内部类定义迭代器，可以直接使用外部类的属性
    private class ConcreteIterator implements MyIterator{

        // 定义游标用于记录遍历时的位置
        private int cursor;

        @Override
        public void first() {
            cursor = 0;
        }

        @Override
        public void next() {
            if (cursor != list.size()){
                cursor++;
            }
        }

        @Override
        public boolean hasNext() {
            return cursor < list.size() ;
        }

        @Override
        public boolean isFirst() {
            return cursor == 0;
        }

        @Override
        public boolean isLast() {
            return cursor == list.size() - 1;
        }

        @Override
        public Object getCurrentObj() {
            return list.get(cursor);
        }
    }
}
